/*
 * Copyright (c) 2000-2017 wanglei. All rights reserved.
 * TeamDev PROPRIETARY and CONFIDENTIAL.
 * Use is subject to license terms.
 */

package com.xhb.ui;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.teamdev.jxbrowser.cookie.Cookie;
import com.teamdev.jxbrowser.cookie.CookieStore;
import com.teamdev.jxbrowser.view.swing.BrowserView;
import com.xhb.biz.constant.UserConfigConstant;
import com.xhb.biz.job.UserDataSyncJob;
import com.xhb.biz.po.ConfigPO;
import com.xhb.biz.service.ConfigService;
import com.xhb.ui.resources.Resources;
import org.noear.solon.Solon;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author tanyukun.
 */
public class LoginLogoutFrame extends JFrame implements ActionListener {

    JButton loginButton, exitButton, logoutButton;
    JTextField userNameField;
    JPasswordField passwordField;

    /**
     * 标签页的登录按钮
     */
    ToolBar.ActionButton loginActButton;

    BrowserView localBrowserView;

    public LoginLogoutFrame(ToolBar.ActionButton loginButton, BrowserView browserView) {
        loginActButton = loginButton;
        localBrowserView = browserView;
        //设置窗体宽高
        this.setSize(350, 200);
        //设置窗口居中显示
        this.setLocationRelativeTo(null);
        //设置关闭窗口结束程序
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //设置窗体禁止调节大小
        this.setResizable(false);
        //创建面板
        JPanel jPanel = new JPanel();

        //布局设置为空，之后可以手动设置组件的坐标位置和大小
        jPanel.setLayout(null);
        // 判断当前是否已经登陆
        Solon.context().getBeanAsync(ConfigService.class, service -> {
            ConfigPO configPo = service.selectUserConfigByKey(UserConfigConstant.USER_TOKEN_KEY);
            if (null == configPo) {
                loginFrame(jPanel);
            } else {
                logoutFrame(jPanel);
            }
        });
        // 退出按钮
        exitButton = new JButton("关闭");
        exitButton.setBounds(200, 100, 80, 25);
        //监听事件
        exitButton.addActionListener(this);
        jPanel.add(exitButton);

    }

    private void loginFrame(JPanel jPanel) {

        this.setTitle("用户登录界面");

        //创建JLabel(用户名)
        JLabel userLabel = new JLabel("用户名:");
        userLabel.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        //定义组件的位置和宽高
        userLabel.setBounds(10, 20, 80, 25);
        //把组件添加到JPanel上
        jPanel.add(userLabel);

        //创建文不域用于用户输入
        userNameField = new JTextField(20);
        //设置文本域的位置和宽高
        userNameField.setBounds(100, 20, 165, 25);
        //把文本域组件添加上
        jPanel.add(userNameField);

        //创建JLabel(密码)
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        //设置位置和大小
        passwordLabel.setBounds(10, 50, 80, 25);
        //添加组件
        jPanel.add(passwordLabel);

        //密码文本域输入 密码输入框，输入密码自动隐藏
        passwordField = new JPasswordField();
        //JTextField password_text = new JTextField(20);
        passwordField.setBounds(100, 50, 165, 25);

        jPanel.add(passwordField);

        //登录按钮
        loginButton = new JButton("登录");
        loginButton.setBounds(80, 100, 80, 25);
        loginButton.addActionListener(this);

        jPanel.add(loginButton);

        //添加面板
        this.add(jPanel);
        //设置可见
        this.setVisible(true);
    }


    private void logoutFrame(JPanel jPanel) {

        this.setTitle("用户注销界面");

        //创建JLabel(用户名)
        JLabel userLabel = new JLabel("已登录，确认注销吗？");
        userLabel.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        //定义组件的位置和宽高
        userLabel.setBounds(100, 20, 165, 25);
        //把组件添加到JPanel上
        jPanel.add(userLabel);

        //注销按钮
        logoutButton = new JButton("注销");
        logoutButton.setBounds(80, 100, 80, 25);
        logoutButton.addActionListener(this);
        jPanel.add(logoutButton);

        //添加面板
        this.add(jPanel);
        //设置可见
        this.setVisible(true);
    }


    @SuppressWarnings("deprecation")
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == loginButton) {
            loginButton.setEnabled(false);
            String userName = userNameField.getText();
            String pws = passwordField.getText();
            if (StrUtil.isBlank(userName) || StrUtil.isBlank(pws)) {
                JOptionPane.showMessageDialog(null, "请输入用户名和密码！");
                return;
            }
            ConfigService service = Solon.context().getBean(ConfigService.class);
            JSONObject loginUser = service.login(userName, pws);
            JSONObject dataObj = loginUser.getJSONObject("data");
            String code = loginUser.getStr("code");
            if (!"200".equals(code) || null == dataObj) {
                JOptionPane.showMessageDialog(null, loginUser.getStr("message", "登陆失败！"));
            } else {
                // 保存登录 token 到 config 表
                service.saveLoginToken(dataObj);
                // 跑一次用户数据同步定时任务
                try {
                    Solon.context().getBeanAsync(UserDataSyncJob.class, UserDataSyncJob::run);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
//                JOptionPane.showMessageDialog(null, "登录成功！");
                loginActButton.setIcon(Resources.getIcon("login.png"));
                // 浏览器用户登陆后就给标签页添加 cookie 以访问服务端页面
                Cookie cookie = service.getCookie();
                CookieStore cookieStore = localBrowserView.getBrowser().profile().cookieStore();
                cookieStore.set(cookie);
                cookieStore.persist();
                this.setVisible(false);
            }
            loginButton.setEnabled(true);
        }
        if (e.getSource() == exitButton) {
            this.dispose();
        }
        if (e.getSource() == logoutButton) {
            logoutButton.setEnabled(false);
            ConfigService configService = Solon.context().getBean(ConfigService.class);
            configService.logout(localBrowserView);
            configService.delUserConfigByKey(UserConfigConstant.USER_TOKEN_KEY);
            loginActButton.setIcon(Resources.getIcon("logout.png"));
            logoutButton.setEnabled(true);
            this.dispose();
        }
    }
}
